package manager

import (
	"errors"
	"time"

	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/model/manager"
	managerReq "gitcode.com/G-YT/baoyou/server/model/manager/request"
	"gitcode.com/G-YT/baoyou/server/utils"
	"gorm.io/gorm"
)

type HealthManagerService struct {
}

func (healthManagerService *HealthManagerService) GetHealthManagerInfo(id uint) (healthManager manager.HealthManager, err error) {
	//err := global.GVA_DB.Debug().Preload("ServiceStation").Preload("ServiceStation.CreatorInfo").Where("hm_id = ?", id).First(&hm).Error
	//return hm, err
	err = global.GVA_DB.Where("hm_id = ?", id).Preload("ServiceStation", func(db *gorm.DB) *gorm.DB {
		return db.Preload("CreatorInfo")
	}).First(&healthManager).Error
	return
}

// CreateHealthManager 注册健管师
// Author [G-YT](https://gitcode.com/G-YT)
func (healthManagerService *HealthManagerService) CreateHealthManager(info managerReq.RegisterRequest) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var existing manager.HealthManager
		findErr := tx.Where("phone = ?", info.Phone).First(&existing).Error
		if findErr == nil {
			if existing.RegisterStatus == 2 {
				updates := map[string]interface{}{
					"service_station_id": info.ServiceStationID,
					"password":           utils.BcryptHash(info.Password),
					"name":               info.Name,
				}
				if err := tx.Model(&manager.HealthManager{}).Where("hm_id = ?", existing.HmID).Updates(updates).Error; err != nil {
					return err
				}
				return nil
			}
			if existing.RegisterStatus == 0 {
				return errors.New("注册已申请，请联系服务站进行审核！")
			}
			if existing.RegisterStatus == 1 {
				return errors.New("注册已通过，请联系服务站进行审核！")
			}
			return nil
		}
		if !errors.Is(findErr, gorm.ErrRecordNotFound) {
			return findErr
		}
		registerInfo := manager.HealthManager{
			ServiceStationID:    info.ServiceStationID,
			Phone:               info.Phone,
			Name:                info.Name,
			CreatedAt:           time.Now(),
			CertificationStatus: 0,
			RegisterStatus:      0,
			PromoteNum:          utils.Pointer(0),
			ServedNum:           utils.Pointer(0),
			Password:            utils.BcryptHash(info.Password),
		}
		if err := tx.Create(&registerInfo).Error; err != nil {
			return errors.New("创建注册健管师信数据失败")
		}
		targetPlan := manager.TargetPlan{
			HmID: registerInfo.HmID,
		}
		if err := tx.Create(&targetPlan).Error; err != nil {
			return err
		}
		return nil
	})
}

// FindManagerByWhere 通过条件获取单条健管师信息
// Author: [g-qs](https://github.com/g-qs)
func (healthManagerService *HealthManagerService) FindManagerByWhere(condition map[string]interface{}, fields string) (info *manager.HealthManager, err error) {
	err = global.GVA_DB.Select(fields).Where(condition).Limit(1).First(&info).Error
	return
}

// Login 登陆
// Author: [g-qs](https://github.com/g-qs)
func (healthManagerService *HealthManagerService) Login(userReq *manager.HealthManager) (result *manager.HealthManager, err error) {
	var managerInfo manager.HealthManager
	err = global.GVA_DB.Where("phone = ?", userReq.Phone).First(&managerInfo).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.New("该手机号不存在，请先注册")
	}
	if err == nil {
		if ok := utils.BcryptCheck(userReq.Password, managerInfo.Password); !ok {
			return nil, errors.New("密码错误")
		}
	}
	return &managerInfo, err
}

// UpdateManagerByWhere 根据条件更新健管师
func (healthManagerService *HealthManagerService) UpdateManagerByWhere(condition map[string]interface{}, fields map[string]interface{}) (manager *manager.HealthManager, err error) {
	err = global.GVA_DB.Model(&manager).Where(condition).Updates(fields).Error
	return
}

// UpdateManagerByID 根据ID更新健管师允许修改的信息
func (healthManagerService *HealthManagerService) UpdateManagerByID(id uint, req managerReq.UpdateManagerRequest) (mm *manager.HealthManager, err error) {
	updates := map[string]interface{}{
		"avatar":               req.Avatar,
		"name":                 req.Name,
		"sex":                  req.Sex,
		"phone":                req.Phone,
		"IDNumber":             req.IDNumber,
		"certification_images": req.CertificationImages,
		"certification_no":     req.CertificationNo,
	}
	if err = global.GVA_DB.Model(&manager.HealthManager{}).Where("hm_id = ?", id).Updates(updates).Error; err != nil {
		return nil, err
	}
	var hm manager.HealthManager
	if err = global.GVA_DB.Preload("ServiceStation").Preload("ServiceStation.CreatorInfo").Where("hm_id = ?", id).First(&hm).Error; err != nil {
		return nil, err
	}
	return &hm, nil
}

// ChangePassword 修改密码
func (healthManagerService *HealthManagerService) ChangePassword(phone string, hmID uint, old, new string) error {
	var hm manager.HealthManager
	if err := global.GVA_DB.Where("phone = ?", phone).First(&hm).Error; err != nil {
		return err
	}
	if hm.HmID != hmID {
		return errors.New("无权修改该账号密码")
	}
	if ok := utils.BcryptCheck(old, hm.Password); !ok {
		return errors.New("旧密码错误")
	}
	return global.GVA_DB.Model(&manager.HealthManager{}).Where("hm_id = ?", hmID).Update("password", utils.BcryptHash(new)).Error
}
